<?php

class SiteController extends Controller
{
  public function actionError()
  {
    if ($error = Yii::app()->errorHandler->error) {
      if (Yii::app()->request->isAjaxRequest)
        echo $error['message'];
      else
        $this->render('error', array(
            'error' => $error
        ));
    }
  }

  public function actionIndex()
  {
    //主页
    $lesson = LessonService::instance()->getList(10, true);
    $bank = QuestionBankService::instance()->getList(10, true);
    $issue = IssueService::instance()->getList(10, false);
    $topic = TopicService::instance()->getTopicList(10, true);
    $this->render('index', array(
        'lesson' => $lesson,
        'bank' => $bank,
        'issue' => $issue,
        'topic' => $topic
    ));
  }


  /**
   * 登陆处理
   * @param string $url 登陆后跳转地址
   */
  public function actionLogin($url = '')
  {
    if (Yii::app()->request->isPostRequest) {
      $data = $this->filter($_POST);
      $identity = new UserIdentity($data['username'], $data['password']);
      if ($identity->authenticate()) {
        Yii::app()->user->login($identity, 3600 * 24 * 7);
        if (Yii::app()->user->getState('type') != $data['type']) {
          $this->jsMsg('用户角色错误!');
        } else {
          //跳转至相应的控制器
          if (empty($url)) {
            if (Yii::app()->user->getState('type') == 1) {
              $this->redirect(Yii::app()->createUrl('student/index'));
            } elseif (Yii::app()->user->getState('type') == 2) {
              $this->redirect(Yii::app()->createUrl('teacher/index'));
            } elseif (Yii::app()->user->getState('type') == 3) {
              $this->redirect(Yii::app()->createUrl('admin/index'));
            }
          } else {
            $this->redirect($url);
          }
        }
      } else {
        $this->jsMsg($identity->errorMessage);
      }
    } else {
      $this->render('login');
    }
  }

  /**
   * 注册
   */
  public function actionRegister()
  {
    if (Yii::app()->request->isPostRequest) {
      $result = UserService::instance()->post($this->filter($_POST));
      if ($result === true) {
        $this->jsMsg('注册成功!', Yii::app()->createUrl('site/index'));
      } else {
        $this->jsMsg($this->getError($result));
      }
    } else {
      $this->render('register');
    }
  }
}